﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kelper.Domain.Models;
using Kelper.Infrastructure.Helpers;

namespace Kelper.Infrastructure.ModelBinders
{
    public class IngredientsModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            try
            {
                return GetAttemptedValue(bindingContext)
                    .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(i => i.Trim().Capitalize())
                    .Where(i => i != "")
                    .Distinct()
                    .Select(i => new Ingredient { Name = i })
                    .ToList();
            }
            catch
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Invalid ingredient or ingredients");
                return new List<Ingredient>();
            }
        }

        // This method is virtual and protected so that it can be overriden for the
        // sake of unit tests
        protected virtual string GetAttemptedValue(ModelBindingContext bindingContext)
        {
            ValueProviderResult value =
                bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            string attemptedValue = value == null ? "" : value.AttemptedValue ?? "";

            return attemptedValue;
        }
    }
}